package com.lg.concurrent.atomic;

import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceTest {

    public static class Student2 {

        private String name;

        private Integer age;

        public Student2() {
        }

        public Student2(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }
    }



    public final static AtomicReference<Student2> atomicStudent = new AtomicReference<Student2>();
    public final static Student2 student1 = new Student2("a", 1);
    public final static Student2 student2 = new Student2("b", 2);

    public static void main(String[] args) {
        //初始值为student1对象
        atomicStudent.set(student1);

        for (int i = 0; i < 10; i++) {
            new Thread() {
                public void run() {
                    try {
                        //为了 使得控制台打印的 更改student1的线程 能显示出不一样 每个线程随机停顿 多执行几次能看出效果
                        Thread.sleep(Math.abs((int) Math.random() * 100));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //预期值 student1和 当前值（上面的atomicStudent.set(student1);）相等时候 赋予student2新的值
                    if (atomicStudent.compareAndSet(student1, student2)) {
                        System.out.println(Thread.currentThread().getId() + "Change value");
                        System.out.println(atomicStudent.get().getName() + ":" + atomicStudent.get().getAge());
                    } else {
                        System.out.println(Thread.currentThread().getId() + "Failed");
                    }
                }

                ;
            }.start();
        }
    }


}
